package com.ptmall.app.base;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;


import com.facebook.stetho.common.LogUtil;
import com.ptmall.app.App;
import com.ptmall.app.MainActivity;
import com.ptmall.app.R;
import com.ptmall.app.base.theme.Eyes;
import com.ptmall.app.bean.model.db.Account;
import com.ptmall.app.net.base.Result;
import com.ptmall.app.utils.RxBus;
import com.ptmall.app.utils.RxSchedulers;
import com.ptmall.app.view.MyProgressDialog;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;


public abstract class BaseMvpActivity<T extends BaseMvpPresenter> extends FragmentActivity implements ActivityCompat.OnRequestPermissionsResultCallback{

    private static final String TAG = "BaseMvpActivity";

    private CompositeDisposable mSubscriptions;


    //Toast
    private Toast mToast;

    private InputMethodManager mInputManager;

    protected T mPresenter;

    protected MyProgressDialog mProgressDialog;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        addSubscription(subscribeEvents());

        mInputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

    }

    //设置layout
    public void setView(int layoutResID) {
        setContentView(layoutResID);
        Eyes.setStatusBarLightMode(this, 0xff3E4558);
        try {
            initViews();
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            initEvents();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public abstract void initViews();

    public abstract void initEvents();


    //RXBus 界面间通信
    protected void addSubscription(Disposable disposable) {
        if (disposable == null) {
            return;
        }
        if (mSubscriptions == null) {
            mSubscriptions = new CompositeDisposable();
        }
        mSubscriptions.add(disposable);
    }

    //RXBus 界面间通信
    protected Disposable subscribeEvents() {
        return RxBus
                .getInstance()
                .toObservable()
                .compose(RxSchedulers.io_main())
                .subscribe(this::succeed, this::failure);
    }

    /**
     * RXBus 收到界面间通信
     * @param obj
     */
    public void succeed(Object obj) {

    }

    /**
     * RXBus 收到界面间通信 失败
     *
     * @param throwable
     */
    public void failure(Throwable throwable) {
        LogUtil.i(TAG, Log.getStackTraceString(throwable));
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        if (mSubscriptions != null) {//解除RxBus通信
            mSubscriptions.clear();
        }
    }
    /* #####################RXBus En######################## */

    /* #####################基本View Start######################## */
    @Override
    public void startActivity(Intent intent) {
        super.startActivity(intent);
        overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            if (getCurrentFocus() != null && getCurrentFocus().getWindowToken() != null) {
                mInputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
        return super.dispatchTouchEvent(ev);
    }
    /* #####################基本View End######################## */


    /* #####################BaseMvpView################################################# Start */

    /**
     * 显示processDialog
     * @param msg 可以为空
     */
    public void showLoading(String msg) {
        if (null == mProgressDialog) {
            if (TextUtils.isEmpty(msg)) {
                mProgressDialog = new MyProgressDialog(this,getString(R.string.hold_on));
            } else {
                mProgressDialog = new MyProgressDialog(this,msg);
            }
        } else {
            if (!TextUtils.isEmpty(msg)) {
                mProgressDialog.setMsg(msg);
            }
        }
        if (null != mProgressDialog) {
            mProgressDialog.show();
        }
    }

    /**
     * 显示processDialog
     * @param msgId 可以为空
     */
    public void showLoading(int msgId) {
        String msg = getString(msgId);
        if (null == mProgressDialog) {
            if (TextUtils.isEmpty(msg)) {
                mProgressDialog = new MyProgressDialog(this,getString(R.string.hold_on));
            } else {
                mProgressDialog = new MyProgressDialog(this,msg);
            }
        } else {
            if (!TextUtils.isEmpty(msg)) {
                mProgressDialog.setMsg(msg);
            }
        }
        if (null != mProgressDialog) {
            mProgressDialog.show();
        }
    }

    public void hideLoading() {
        if (null != mProgressDialog) {
            mProgressDialog.dismiss();
        }
    }

    public void showMsg(int msg) {
        String message = getString(msg);
        if (TextUtils.isEmpty(message)) {
            return;
        }
        if (null == mToast) {
            mToast = Toast.makeText(this, message, Toast.LENGTH_SHORT);
        } else {
            mToast.setText(message);
        }
        mToast.show();
    }

    public void showMsg(String msg) {
        if (null == mToast) {
            mToast = Toast.makeText(this, msg, Toast.LENGTH_SHORT);
        } else {
            mToast.setText(msg);
        }
        mToast.show();
    }

    public void showErrorResult(Result result, String defaultInfo) {
        if (null != result && !TextUtils.isEmpty(result.getInfo())) {
            showMsg(result.getInfo());
        } else {//默认提示
            if (!TextUtils.isEmpty(defaultInfo)) {
                showMsg(defaultInfo);
            }
        }
    }

    public void showErrorResult(Result result, int defaultInfo) {
        if (null != result && !TextUtils.isEmpty(result.getInfo())) {
            showMsg(result.getInfo());
        } else {//默认提示
            String info = getString(defaultInfo);
            if (!TextUtils.isEmpty(info)) {
                showMsg(info);
            }
        }
    }


    public Activity getActivity() {
        return this;
    }

    public Context getContext() {
        return this;
    }
    /* #####################BaseMvpView################################################# End */


    /**
     * 是否登录中
     * @return
     */
    protected boolean isLogined() {//是否已登录
        if (null == MainActivity.MEMBERID || TextUtils.isEmpty(MainActivity.MEMBERID)) {//未登录状态
            return false;
        } else {
            return true;
        }
    }

    //*******************************权限管理****开始*****************************************************//


    private PermissionListener mListener;

    private static final int PERMISSIONREQUSTCODE = 1;

    public void requestRuntimePermisssions(String[] permissions, PermissionListener listener) {

        mListener = listener;
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            //小于6.0的权限直接使用就可以了，不用在申请
            mListener.onGranted();
            return;
        }
        //6.0以及以后的操作
        List<String> permissionList = new ArrayList<String>();
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                permissionList.add(permission);
            }
        }

        if (!permissionList.isEmpty()) {
            ActivityCompat.requestPermissions(this, permissionList.toArray(new String[permissionList.size()]), PERMISSIONREQUSTCODE);
        } else {
            mListener.onGranted();
        }


    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        switch (requestCode) {
            case PERMISSIONREQUSTCODE: {
                //合法检验
                if (grantResults != null && grantResults.length > 0) {
                    List<String> deniedList = new ArrayList<String>();
                    for (int i = 0; i < grantResults.length; i++) {
                        if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                            deniedList.add(permissions[i]);//权限被拒绝了
                        }
                    }

                    if (deniedList.isEmpty()) {
                        mListener.onGranted();
                    } else {
                        //提示未获取权限
                        showMessageOKCancel(this, getString(R.string.permission_denied_alert),
                                (dialog,which)->{
                                    //跳转设置
                                    dialog.dismiss();
                                    Intent intent = new Intent();
                                    intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                    Log.d(TAG, "getPackageName(): " + getPackageName());
                                    Uri uri = Uri.fromParts("package", getPackageName(), null);
                                    intent.setData(uri);
                                    startActivity(intent);
                                },(dialog, which)->{
                                        dialog.dismiss();
                                        mListener.onDenied(deniedList);
                                    }
                                );
                    }
                }
                break;
            }
            default: {
                break;
            }
        }
    }

    private static void showMessageOKCancel(final Activity context, String message, DialogInterface.OnClickListener okListener, DialogInterface.OnClickListener cancelListener) {
        new AlertDialog.Builder(context)
                .setMessage(message)
                .setPositiveButton(R.string.permission_denied_alert_ok, okListener)
                .setNegativeButton(R.string.permission_denied_alert_cancel, cancelListener)
                .create()
                .show();

    }

    //*******************************权限管理***结束******************************************************//

}
